# plugs/ps.py
#
#

""" ps command """

__copyright__ = 'this file is in the public domain'

from ommbot.world import add_cmnd, add_example
from ommbot.generic import ommpopen
import os
import threading

def handle_ps(bot, ievent):
    """ ps .. show ps line of the bot """
    if os.uname()[0] == 'SunOS':
        args = [""] * 5
        args[0] = 'ps'
        args[1] = '-o'
        args[2] = 'user,pid,pcpu,pmem,vsz,rss,tty,s,stime,etime,comm'
        args[3] = '-p'
        args[4] = str(os.getpid())
    else:
        args = [""] * 3
        args[0] = 'ps'
        args[1] = 'wwup'
        args[2] = str(os.getpid())
    try:
        proces = ommpopen(args)
    except Exception, ex:
        ievent.reply('error running popen: %s' % str(ex))
        return
    data = proces.fromchild.readlines()
    if not proces.wait():
        result = str(data[1]).strip().split()
        temp1 = "cpu=%s mem=%s vsz=%s rss=%s " % tuple(result[2:6])
        temp2 = "stat=%s started=%s time=%s" % tuple(result[7:10])
        threads = " threads=%s" % str(threading.activeCount())
        ievent.reply(temp1+temp2+threads)
    else:
        ievent.reply('error executing ps')

add_cmnd('ps', handle_ps, ['USER', 'WEB'])
add_example('ps', 'show ps line of the bot', 'ps')
